﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Threading;
using NLog;

namespace RestartService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        System.Timers.Timer timerRestarter;  //计时器
        NlogHelper logHelper = new NlogHelper(LogLevel.Info);
        protected override void OnStart(string[] args)
        {
            timerRestarter = new System.Timers.Timer();
            timerRestarter.Interval = 600;  //设置计时器事件间隔执行时间  600mm执行一次
            timerRestarter.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timerRestarter.Enabled = true;
        }

        protected override void OnStop()
        {
            timerRestarter.Enabled = false;
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                string[] restartTime = ConfigurationManager.AppSettings["RestartTime"].Split(':');
                int[] restartTimeInt = Array.ConvertAll(restartTime, int.Parse);
                DateTime timeNow = DateTime.Now;
                if (timeNow.Hour == restartTimeInt[0] &&
                    timeNow.Minute == restartTimeInt[1] &&
                    timeNow.Second == restartTimeInt[2])
                {
                    timerRestarter.Enabled = false;

                    List<string> services = ConfigurationManager.AppSettings["ServiceNames"].Split(new char[] { ',' }).ToList();

                    if (services != null && services.Count > 0)
                    {
                        foreach (var item in services)
                        {
                            ServiceController service = new ServiceController(item);
                            try
                            {
                                if (service.Status == ServiceControllerStatus.Running)
                                {
                                    service.Stop();
                                    service.WaitForStatus(ServiceControllerStatus.Stopped,new TimeSpan(30));

                                    service.Start();
                                    service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(30));
                                }
                                if (service.Status != ServiceControllerStatus.Running)
                                {
                                    service.Start();
                                    service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(30));
                                }
                                logHelper.logger.Info($"重启服务：[{item}]成功！");
                            }
                            catch (Exception exin)
                            {
                                logHelper.logger.Info(exin);
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                logHelper.logger.Info(ex);
            }
            finally {
                timerRestarter.Enabled = true;
            }

        }
    }
}
